import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:photo_frame/net/http_manager.dart';
import 'package:photo_frame/router/router_context.dart';
import 'package:photo_frame/widgets/app_bar_widget.dart';
import 'package:provider/provider.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:flutter_gen/gen_l10n/app_localizations.dart';

class RegisterPage extends StatefulWidget {
  const RegisterPage({super.key});

  @override
  State<StatefulWidget> createState() {
    return RegisterState();
  }
}

class RegisterState extends State<RegisterPage> {
  TextEditingController emailController = TextEditingController();
  TextEditingController passwordController = TextEditingController();
  TextEditingController password2Controller = TextEditingController();

  @override
  Widget build(BuildContext context) {
    SharedPreferences.getInstance()
        .then((e) => {print("object ${e.getString("token")}")});
    return Scaffold(
      appBar: commonAppBar(AppLocalizations.of(context)!.register),
      body: Padding(
        padding: const EdgeInsets.symmetric(horizontal: 15),
        child: ChangeNotifierProvider(
          create: (context) => RegisterViewModel(),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Container(
                margin: const EdgeInsets.only(top: 20),
                child: TextField(
                  cursorColor: Color(0xff3F74EF), // 设置光标颜色
                  controller: emailController,
                  style: TextStyle(fontWeight: FontWeight.normal, fontSize: 14),
                  decoration: InputDecoration(
                    hintText: AppLocalizations.of(context)!.emailAddress,
                    hintStyle:
                        const TextStyle(color: Color(0xff999999), fontSize: 14),
                    fillColor: Color(0xffEAECEE),
                    contentPadding: const EdgeInsets.symmetric(
                        horizontal: 26, vertical: 18),
                    filled: true,
                    border: OutlineInputBorder(
                      borderSide: BorderSide.none,
                      borderRadius: BorderRadius.circular(28.5),
                    ),
                  ),
                ),
              ),
              Container(
                margin: const EdgeInsets.only(top: 10),
                child: TextField(
                  cursorColor: Color(0xff3F74EF), // 设置光标颜色
                  controller: passwordController,
                  style: TextStyle(fontWeight: FontWeight.normal, fontSize: 14),
                  decoration: InputDecoration(
                    hintText: AppLocalizations.of(context)!.inputPassword,
                    hintStyle:
                        const TextStyle(color: Color(0xff999999), fontSize: 14),
                    fillColor: Color(0xffEAECEE),
                    contentPadding: const EdgeInsets.symmetric(
                        horizontal: 26, vertical: 18),
                    filled: true,
                    border: OutlineInputBorder(
                      borderSide: BorderSide.none,
                      borderRadius: BorderRadius.circular(28.5),
                    ),
                  ),
                ),
              ),
              Container(
                margin: const EdgeInsets.only(top: 10),
                child: TextField(
                  cursorColor: Color(0xff3F74EF), // 设置光标颜色
                  controller: password2Controller,
                  style: TextStyle(fontWeight: FontWeight.normal, fontSize: 14),
                  decoration: InputDecoration(
                    hintText:
                        AppLocalizations.of(context)!.enterYourPasswordAgain,
                    hintStyle:
                        const TextStyle(color: Color(0xff999999), fontSize: 14),
                    fillColor: Color(0xffEAECEE),
                    contentPadding: const EdgeInsets.symmetric(
                        horizontal: 26, vertical: 18),
                    filled: true,
                    border: OutlineInputBorder(
                      borderSide: BorderSide.none,
                      borderRadius: BorderRadius.circular(28.5),
                    ),
                  ),
                ),
              ),
              Consumer<RegisterViewModel>(
                builder: (context, value, child) => Visibility(
                  child: Opacity(
                    opacity: context.watch<RegisterViewModel>().errMsg != null
                        ? 1
                        : 0,
                    child: Container(
                      margin: const EdgeInsets.only(
                        left: 29,
                        top: 12,
                      ),
                      child: Text(
                        "*${value.errMsg}",
                        style: const TextStyle(
                            color: Color(0xffFF4747), fontSize: 11),
                      ),
                    ),
                  ),
                ),
              ),
              Builder(builder: (context) {
                return CupertinoButton (
                  padding: EdgeInsets.zero,
                  onPressed: () {
                    context
                        .read<RegisterViewModel>()
                        .sendCode(context, emailController.text,
                            passwordController.text, password2Controller.text)
                        .then((e) {
                      if (e == true) {
                        ARouter.instance.pagePush("/verificationCode",
                            arguments: {
                              "email": emailController.text,
                              "password": passwordController.text
                            });
                      }
                    });
                  },
                  child: Container(
                    margin: const EdgeInsets.only(top: 15),
                    height: 57,
                    decoration: BoxDecoration(
                        color: const Color(0xff3F74EF),
                        borderRadius: BorderRadius.circular(28.5)),
                    child: Center(
                        child: Text(
                      AppLocalizations.of(context)!.register,
                      style: TextStyle(
                          fontSize: 14,
                          color: Colors.white, fontWeight: FontWeight.bold),
                    )),
                  ),
                );
              }),
            ],
          ),
        ),
      ),
    );
  }
}

class RegisterViewModel extends ChangeNotifier {
  String? errMsg;

  Future<dynamic> sendCode(BuildContext context, String email, String password,
      String password2) async {
    if (email.isEmpty) {
      errMsg = AppLocalizations.of(context)!.pleaseCheckYourEmail;
      notifyListeners();
      return Future.value(null);
    }
    if (password.isEmpty || password2.isEmpty || password != password2) {
      errMsg = AppLocalizations.of(context)!.pleaseCheckYourPassword;
      notifyListeners();
      return Future.value(null);
    }

    if (password.length < 8) {
      errMsg = AppLocalizations.of(context)!.password_too_short;
      notifyListeners();
      return Future.value(null);
    }
    await EasyLoading.show(
      maskType: EasyLoadingMaskType.black,
    );
    return HttpManager.instance
        .doRequest("/sendcode", parameters: {"email": email}).then((e) {
      if (e.isSuccess) {
        Fluttertoast.showToast(msg: AppLocalizations.of(context)!.codeSended);
        return true;
      } else {
        Fluttertoast.showToast(
            msg: e.msg ?? AppLocalizations.of(context)!.failedSendCode);
        return false;
      }
    }).catchError((e) {
      Fluttertoast.showToast(msg: AppLocalizations.of(context)!.failedSendCode);
      return false;
    }).whenComplete(() {
      EasyLoading.dismiss();
    });
  }
}
